package com.whh.starter.web;




import com.whh.starter.config.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SystemFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(SystemFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //real Pre-processing
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String correlationId = httpServletRequest.getHeader("x-request-id");
        RequestContext.createContext(correlationId);
        String method = httpServletRequest.getMethod();
        correlationId = RequestContext.getCurrentContext().getCorrelationId();
        log.info("Http Request RequestId : " + correlationId + " Start !");
        log.info("Authorization: {}", httpServletRequest.getHeader("Authorization"));
        log.info("Http Request Information : {\"URI\":\"" + httpServletRequest.getRequestURI() +
                "\",\"Method\":\"" + method +
                "\",\"Accept\":\"" + httpServletRequest.getHeader("Accept") +
                "\",\"Content-Type\":\"" + httpServletRequest.getContentType() +
                "\"}");
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        //当错误请求时会重定向到 /error，重定向前会先清理Context，这样会造成一个问题，MDC/context 依然存在直到下一次请求清理
//        RequestContext.cleanContext();
    }
}
